<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>上传 / 修改头像</span>
      </div>
    </template>
    <el-row type="flex" justify="center" align="middle">
      <el-col :span="5">
        <!--
                auto-upload：设置是否自动上传
                action：设置服务器接口地址
                name：设置上传的文件字段名
                headers：设置上传的请求头
                on-success：设置上传成功的回调函数
               -->
        <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          :headers="{'token':token}"
          action="/dev-api/admin/upload"
          name="file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :auto-upload="true"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" alt="">
          <img v-else :src="defaultAvatar" class="avatar" alt="">
        </el-upload>
        <br/>
        <el-button type="primary" @click="$refs.uploadRef.$el.querySelector('input').click()">
          选择图片
        </el-button>
        <el-button type="success" @click="updateAvatar">
          上传头像
        </el-button>
      </el-col>
    </el-row>
  </el-card>
</template>

<script>
import { mapGetters } from 'vuex'
import api from '@/api/user/user'
import store from '@/store'
import defaultAvatar from '@/assets/avatar/default.png'

export default {
  data() {
    return {
      imageUrl: this.$store.getters.avatar,
      defaultAvatar
    }
  },
  computed: {
    ...mapGetters(['token'])
  },

  methods: {
    // 图片上传成功回调
    handleAvatarSuccess(res) {
      // 渲染图片
      this.imageUrl = res.data
      // 提示信息
      this.$message({
        message: '头像上传成功',
        type: 'success'
      })
    },

    // 修改头像
    updateAvatar() {
      api.updateAvatar(this.imageUrl).then(async response => {
        // 更新头像
        await store.dispatch('user/getInfo')// 重新请求获取用户信息
        //提示信息
        this.$message({
          type: 'success',
          message: '头像更新成功!'
        })
      })
    }

  }
}
</script>

<style>
.page-container {

  margin: 50px;

}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 278px;
  height: 278px;
  display: block;
}
</style>
